package com.someok.utils.file;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import com.someok.utils.Util;


/**
 * Performs zip/unzip operations on files and directories.
 *
 * <p><a href="ZipUtil.java.html"><i>View Source</i></a></p>
 *
 * @version $Revision: 30 $ $Date: 2006-06-08 21:26:40 +0800 (星期四, 08 六月 2006) $
 */
public class ZipUtil {

	/**
	 * Unpacks a zip file to the target directory.
	 *
	 * @param zipFile zip file
	 * @param destDir destination directory
	 *
	 * @throws IOException
	 */
	public static void unzip(File zipFile, File destDir) throws IOException {
		ZipFile zip = new ZipFile(zipFile);
		Enumeration en = zip.entries();
		int bufSize = 8196;

		while (en.hasMoreElements()) {
			ZipEntry entry = (ZipEntry) en.nextElement();
			File file = (destDir != null) ? new File(destDir, entry.getName()) : new File(entry.getName());
			if (entry.isDirectory()) {
				if (!file.mkdirs()) {
					if (file.isDirectory() == false) {
						throw new IOException("Error creating directory: " + file);
					}
				}
			} else {
				File parent = file.getParentFile();
				if (parent != null && !parent.exists()) {
					if (!parent.mkdirs()) {
						if (file.isDirectory() == false) {
							throw new IOException("Error creating directory: " + parent);
						}
					}
				}

				InputStream in = zip.getInputStream(entry);
				try {
					OutputStream out = new BufferedOutputStream(new FileOutputStream(file), bufSize);
					try {
						Util.copyPipe(in, out, bufSize);
					} finally {
						out.close();
					}
				} finally {
					in.close();
				}
			}
		}
	}

}
